package com.bytecodes.eaulas.conexion;

import com.bytecodes.eaulas.comun.servicios.*;
import com.bytecodes.eaulas.beans.*;

import java.util.*;
import java.util.List;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*; 
import javax.swing.*;
import javax.swing.table.*;
import java.awt.Dimension;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

/**
 *
 * Pantalla principal de Consultas
 * @author Robert Artesona Torres
 */
public class PantallaConsulta extends javax.swing.JPanel {

        /**
	 * 
	 */
	private JLabel Titulo = null;
	private static final long serialVersionUID = 7537326094598106013L;
        private EAulasServiciosInterface remoto;       
        private ArrayList<String> idclients = new ArrayList<String>();
        private String ClienteId;
        private JTable tb = new JTable(1000,8);
        private Integer EsConsulta = 0;
        JButton btAcceptar = new JButton();
        JButton btSi = new JButton();
        JButton btNo = new JButton();
	List<Reserva> listaBookings = null;
	JPanel pDades1 = new JPanel();
	private JTextField Motiu = new JTextField();
        private String filtro;
        
                       
    /** 
     * Creates new form PantallaClientes
     */
    public PantallaConsulta(EAulasServiciosInterface rem, String idCliente, Integer Consulta) {
        remoto = rem;
        ClienteId = idCliente;
        EsConsulta = Consulta;
        initComponents();
        if (!ClienteId.equals("")) {
            // Solament veurem lo d'aquest client.
            jLabel2.setVisible(false);
            jComboClients.setVisible(false);
        }        
    }
        
    private String SumRecarrec(Double importe, String fecha) {
        final long MILLSECS_PER_DAY = 24 * 60 * 60 * 1000;
        String Resultado = "0";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");      
        Date hoy = new Date();      
        try { 
            Date fechaInicio = df.parse(fecha); 
            long diferenciaMils = (fechaInicio.getTime() - hoy.getTime()) / MILLSECS_PER_DAY;
            diferenciaMils = diferenciaMils + 1;
            int por = 20;                 
            if (diferenciaMils < 7) por = 50;
            importe = (importe*por)/100;
            
            Resultado = TDSLanguageUtils.getMessage("mostrar.dias.mensaje1") + " " + diferenciaMils + " " +
                        TDSLanguageUtils.getMessage("mostrar.dias.mensaje2") + " " + String.valueOf(importe);
            return Resultado;
            } catch (ParseException e) { 
                e.printStackTrace(); 
            } 
        return Resultado;
    }  
    
    /**
     * 
     */
    private void initComponents() {
               
        // Combo Activas
                        
        jLabel1 = new javax.swing.JLabel();
        jComboActivas = new javax.swing.JComboBox();
        // Combo Clientes
        jLabel2 = new javax.swing.JLabel();
        jComboClients = new javax.swing.JComboBox();
        // Graella de dades
        tb.setRowSelectionAllowed(true);
        tb.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tb.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tb.setPreferredScrollableViewportSize(new Dimension (600,150));
        //        
        tb.setModel(new ListaOrden("",""));
        DefineReixa();

        JScrollPane panelScroll = new JScrollPane(tb);
        // Mensaje
        jLabel3 = new javax.swing.JLabel();
        
        // Combo Activas
        jLabel1.setText(TDSLanguageUtils.getMessage("panelConsultaAulas.activas"));

        if ((EsConsulta == 2)||(EsConsulta == 1)) {
            jComboActivas.setModel(new javax.swing.DefaultComboBoxModel(new String[] {TDSLanguageUtils.getMessage("panelConsultaAulas.TipoAct.Activa")}));            
        }
        
        if ((EsConsulta == 0)||(EsConsulta == 3)) {
        jComboActivas.setModel(new javax.swing.DefaultComboBoxModel(new String[] {TDSLanguageUtils.getMessage("panelConsultaAulas.TipoAct.Activa")
                								, TDSLanguageUtils.getMessage("panelConsultaAulas.TipoAct.Cancelada")
                								, TDSLanguageUtils.getMessage("panelConsultaAulas.TipoAct.Ejecutada")
        									, TDSLanguageUtils.getMessage("panelConsultaAulas.TipoAct.Inactiva") }));
        }
        
        jComboActivas.addActionListener(new java.awt.event.ActionListener() {
               public void actionPerformed(java.awt.event.ActionEvent evt) {
                   filtro = jComboActivas.getSelectedItem().toString(); 
                   ompleClients();                   
             }
           });  
        
        // Combo Clientes
        jLabel2.setText(TDSLanguageUtils.getMessage("panelConsultaAulas.clientes"));
        // Mensaje
        jLabel3.setText(TDSLanguageUtils.getMessage("orden.reixa.mensaje"));
        // Carregem els clients
        jComboClients.addActionListener(new java.awt.event.ActionListener() {
               public void actionPerformed(java.awt.event.ActionEvent evt) {
                   filtro = jComboActivas.getSelectedItem().toString(); 
                   String idpos = ClienteId;
                   int selected = jComboClients.getSelectedIndex();    
                   if ((selected > -1) && (!idclients.isEmpty())) {
                       idpos = idclients.get(selected);
                   }
                   ClienteId = idpos;
                   ompleReixa();
             }
           });  
                
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
                
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()                
                .addContainerGap(900, Short.MAX_VALUE))
        );
        
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()                
                .addContainerGap(430, Short.MAX_VALUE))
        );

        Titulo = new JLabel();
        Titulo.setBounds(new Rectangle(500, 10, 380, 16));
        Titulo.setForeground(new Color(255, 51, 51));
        
	this.setBackground(Color.WHITE);                
        
        if (EsConsulta == 0) Titulo.setText(TDSLanguageUtils.getMessage("orden.titulo.consulta"));
        if (EsConsulta == 3) Titulo.setText(TDSLanguageUtils.getMessage("orden.titulo.consulta"));
        if (EsConsulta == 1) Titulo.setText(TDSLanguageUtils.getMessage("orden.titulo.administrador"));
        if (EsConsulta == 2) Titulo.setText(TDSLanguageUtils.getMessage("orden.titulo.cliente"));
        
        this.add(Titulo,null);
        
	jLabel1.setBounds(new Rectangle(30,20,75,20));
	jLabel2.setBounds(new Rectangle(30,60,75,20));
	jLabel3.setBounds(new Rectangle(30,100,750,20));

	this.add(jLabel1,null);
	this.add(jLabel2,null);
	this.add(jLabel3,null);
        
	jComboActivas.setBounds(new Rectangle(110,20,110,20));
	jComboClients.setBounds(new Rectangle(110,60,180,20));
	this.add(jComboActivas,null);
	this.add(jComboClients,null);
        
        panelScroll.setBounds(new Rectangle(10,130,850,200));
	this.add(panelScroll,null);

        btAcceptar.setText(TDSLanguageUtils.getMessage("orden.boton.mensaje1"));
      
        if (EsConsulta == 0) btAcceptar.setText(TDSLanguageUtils.getMessage("orden.boton.mensaje1"));
        if (EsConsulta == 3) btAcceptar.setText(TDSLanguageUtils.getMessage("orden.boton.mensaje1"));
        if (EsConsulta == 1) btAcceptar.setText(TDSLanguageUtils.getMessage("orden.boton.mensaje2"));
        if (EsConsulta == 2) btAcceptar.setText(TDSLanguageUtils.getMessage("orden.boton.mensaje3"));
        
	btAcceptar.setBounds(new Rectangle(110,350,200,40));
        btAcceptar.addActionListener( new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
                                if ((tb.getSelectedRow() >= 0)&&(jComboClients.getSelectedIndex() >= 0)) {
                                   String nomcli = jComboClients.getSelectedItem().toString(); 
                                   int tipus = jComboActivas.getSelectedIndex();    
                                   int selected = jComboClients.getSelectedIndex();    
                                   String idcli = idclients.get(selected);                                   
                                   filtro  = jComboActivas.getSelectedItem().toString(); 
                                   
                                   if ((EsConsulta == 0)||(EsConsulta == 3)) mostrar(tipus);
                                   if ((EsConsulta == 1)||(EsConsulta == 2)) anularBooking();
                                }
			}
		} );
                
        
	pDades1.setLayout(null);
	pDades1.setBounds( new Rectangle(10,340,850,80) );                
	pDades1.setBorder( BorderFactory.createTitledBorder(TDSLanguageUtils.getMessage("mostrar.titulo1")));
        btSi.setText(TDSLanguageUtils.getMessage("mostrar.boton.aceptar"));
        btNo.setText(TDSLanguageUtils.getMessage("mostrar.boton.cancelar"));
        //
        btSi.setBounds(new Rectangle(550,40,100,30));
        btNo.setBounds(new Rectangle(670,40,100,30));        
        pDades1.add(btSi,null);
        pDades1.add(btNo,null);
        this.add(pDades1,null);
        pDades1.setVisible(false);        
        this.add(btAcceptar,null);        
    }

    private void anularBooking() {
        btAcceptar.setVisible(false);
	jComboActivas.setEnabled(false);
	jComboClients.setEnabled(false);
        tb.setEnabled(false);
        pDades1.setVisible(true);        
        JLabel lbl8 = new JLabel(TDSLanguageUtils.getMessage("mostrar.lbl8"));

        if (EsConsulta == 1) {
            lbl8.setBounds(new Rectangle(30,30,120,20));
            lbl8.setText(TDSLanguageUtils.getMessage("mostrar.lbl8"));            
            Motiu.setBounds(new Rectangle(150,30,250,20));
            pDades1.add(lbl8,null);
            pDades1.add(Motiu,null);                                   
        }
        if (EsConsulta == 2) {
            lbl8.setBounds(new Rectangle(30,30,120,20));
            lbl8.setText(TDSLanguageUtils.getMessage("mostrar.lbl9"));
            Double Au2 = Double.parseDouble((tb.getValueAt(tb.getSelectedRow(), 8)).toString());
            Motiu.setBounds(new Rectangle(150,30,250,20));
            Motiu.setText(SumRecarrec(Au2,(tb.getValueAt(tb.getSelectedRow(), 4)).toString()));
            pDades1.add(Motiu,null);
            pDades1.add(lbl8,null);
            Motiu.setEnabled(false);
        }        
        
        btSi.addActionListener( new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (EsConsulta == 1) {
                    // Grabo al bookings
                    String missatge = Motiu.getText();
                    Integer idBooking = Integer.parseInt((tb.getValueAt(tb.getSelectedRow(), 1)).toString());
                    try {
                        remoto.setUpdateResolt(missatge, idBooking);
                        } catch (Exception eX) {                
                            System.out.println(eX.getMessage());
                                              }        
                    ompleClients();                   
                    ompleReixa();                    
                }
                if (EsConsulta == 2) {
                    // Grabo al bookings
                    Integer idBooking = Integer.parseInt((tb.getValueAt(tb.getSelectedRow(), 1)).toString());
                    try {
                         remoto.setDeleteUser(idBooking);
                    } catch (Exception eX) {                
                         System.out.println(eX.getMessage());
                                              }        
                    ompleReixa();
                }
                pDades1.setVisible(false);
                btAcceptar.setVisible(true);
                tb.setEnabled(true);  
                jComboActivas.setEnabled(true);
                jComboClients.setEnabled(true);                
            }
	});
        
        btNo.addActionListener( new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pDades1.setVisible(false);
                btAcceptar.setVisible(true);
                tb.setEnabled(true);
                jComboActivas.setEnabled(true);
                jComboClients.setEnabled(true);                
            }
	});
    }
            
    private void mostrar(int selected) {
        Integer idBooking = Integer.parseInt((tb.getValueAt(tb.getSelectedRow(), 1)).toString());
        if (idBooking > 0) {
            String missatge = "";
            if (selected == 1) missatge = String.valueOf(tb.getValueAt(tb.getSelectedRow(), 0)).toString()+' ';
            PantallaMostrar pMo = new PantallaMostrar(remoto, idBooking, missatge);
        }
    }
    
    /**
     * 
     */
    private void ompleClients() {         
	List<Usuario> listaUsuarios = null;
            try {
            listaUsuarios = remoto.getTotal(filtro);
            } catch (Exception e) {                
				System.out.println(e.getMessage());
                                  }        
        
        jComboClients.removeAllItems();
        idclients.clear();
        
        if (!listaUsuarios.isEmpty()) {
            for(int i=0;i<listaUsuarios.size();i++){
                Usuario usuario= listaUsuarios.get(i);
                jComboClients.addItem(usuario.getNombre());
                idclients.add(usuario.getCodUsuario());
            }            
        } else jComboClients.addItem(TDSLanguageUtils.getMessage("orden.clientes.nohiha"));
    }

    /**
     * 
     */
    private void ompleReixa() {    
        tb.setModel(new ListaOrden(filtro,ClienteId));
        DefineReixa();
    }

    private void DefineReixa() {    
        int vColIndex = 0;
        TableColumn col = tb.getColumnModel().getColumn(vColIndex);
        int width = 0;
        col.setPreferredWidth(width);        
        col.setResizable(false);
        col.setWidth(0);        
        // Id
        vColIndex = 1;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 70;
        col.setPreferredWidth(width);
        // Aula        
        vColIndex = 2;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 70;
        col.setPreferredWidth(width);
        //  Descripcio
        vColIndex = 3;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 220;
        col.setPreferredWidth(width);
        //  Fecha
        vColIndex = 4;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 100;
        col.setPreferredWidth(width);
        //  Fecha
        vColIndex = 5;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 100;
        col.setPreferredWidth(width);
        //  Personas
        vColIndex = 6;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 80;
        col.setPreferredWidth(width);
        //  Estado
        vColIndex = 7;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 90;
        col.setPreferredWidth(width);
        //  Importe
        vColIndex = 8;
        col = tb.getColumnModel().getColumn(vColIndex);
        width = 80;
        col.setPreferredWidth(width);
    }
    
    //Declaracion de tipos
    private javax.swing.JComboBox jComboActivas;
    private javax.swing.JComboBox jComboClients;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private Vector<Object> vFila;    

/**
 * 
 */
class ListaOrden extends AbstractTableModel
{
    private Vector<String> datosCabecera = new Vector<String>();
    private Vector<Object> datosTabla = new Vector<Object>();
    
    private void setDatosCabecera()
    {
        String cp1 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.bookingId"); 
        String cp2 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.SpaceId"); 
        String cp3 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.SpaceDescription"); 
        String cp4 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.startTime"); 
        String cp5 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.endTime"); 
        String cp6 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.pax"); 
        String cp7 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.status"); 
        String cp8 = TDSLanguageUtils.getMessage("orden.reixa.capcelera.importe"); 
        
        datosCabecera.add("");
        datosCabecera.add(cp1);
        datosCabecera.add(cp2);
        datosCabecera.add(cp3);
        datosCabecera.add(cp4);
        datosCabecera.add(cp5);
        datosCabecera.add(cp6);
        datosCabecera.add(cp7);
        datosCabecera.add(cp8);
        
    }
    
    private void setDatosTabla(String filtro, String idclient)
    {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        NumberFormat formatter = new DecimalFormat("0.00");
        try {
            listaBookings = remoto.getReixa(filtro,idclient);
            } catch (Exception e) {                
				System.out.println(e.getMessage());
                                  }        
        if (!listaBookings.isEmpty()) {
            for(int i=0;i<listaBookings.size();i++){
                Reserva booking = listaBookings.get(i);
                vFila = new Vector<Object>();
                vFila.add(booking.getApunteReserva());
                vFila.add(booking.getIdReserva());
                vFila.add(booking.getIdAula());
                // Falta nombre de la aula
                String spacedescription = "";
                try {
                    spacedescription = remoto.getDescripcio(booking.getIdAula());                    
                    } catch (Exception e) {                
				System.out.println(e.getMessage());
                                  }            
                vFila.add(spacedescription);
                String fechaInicio = df.format(booking.getFechaPeticionInicioReserva());                        
                String fechaFin = df.format(booking.getFechaPeticionFinReserva());                
                
                vFila.add(fechaInicio);
                vFila.add(fechaFin);
                vFila.add(booking.getNumeroOcupantesAula());
                vFila.add(booking.getStatusReserva());
                
                // Falta importe de la aula
                Double importe=0.0;
                try {
                    importe = remoto.getImporte(booking.getIdReserva());                    
                    } catch (Exception e) {                
				System.out.println(e.getMessage());
                                  }                        
                String s = formatter.format(importe); 
                vFila.add(s);
                datosTabla.add(vFila);
            }            
        } else {
                String[] OrdenesCliente = new String[] {
                           "","0","","","","","","",""
                };
                vFila = new Vector<Object>();
                vFila.add(OrdenesCliente[0]);
                vFila.add(OrdenesCliente[1]);
                vFila.add(OrdenesCliente[2]);
                vFila.add(OrdenesCliente[3]);
                vFila.add(OrdenesCliente[4]);
                vFila.add(OrdenesCliente[5]);
                vFila.add(OrdenesCliente[6]);
                vFila.add(OrdenesCliente[7]);
                vFila.add(OrdenesCliente[8]);
                datosTabla.add(vFila);
                }        
    }
    
    public ListaOrden(String filtro,String idclient)
    {
        setDatosCabecera();
        setDatosTabla(filtro,idclient);
    }
    
    public int getColumnCount() 
    { 
	return(((Vector<Object>)datosTabla.get(0)).size()); 
    }

    public String getColumnName(int col) 
    { 
	return((String)datosCabecera.get(col)); 
    }
    
    public boolean getScrollableTrackViewportHeight() 
    { 
	return(true); 
    }

    public boolean getScrollableTrackViewportWidth() 
    { 
	return(true); 
    }

    public int getRowCount() 
    { 
	return(datosTabla.size());
    }

    public Object getValueAt( int fila,int col ) 
    { 
	return(((Vector<Object>)datosTabla.get(fila)).get(col)); 
    }

    public void setValueAt( Object valor,int fila,int col ) 
    {
	((Vector<Object>)datosTabla.get(fila)).set(col,valor);
	// Indica que se ha cambiado
	fireTableDataChanged();
    }

    public boolean isCellEditable(int fila, int columna) 
    {
	return(false);
    }
    
}

}

